<template>
	<view class="page-wrapper">
		<view v-if="order_info">
			<view class="order-num">
				<lang keywords="订单号"></lang>
				：{{ order_info.order_info.real_orderid }}
			</view>
			<view class="pay-num rel border-b">
				<view class="num-box">
					<lang keywords="应付金额"></lang>
					：
					<view class="num block-in">{{ currency }}{{ showCoupon ? order_info.order_info.order_total_money : order_info.pay_config.pay_infact_old }}</view>
				</view>
				<view class="desc-box">{{ order_info.pay_config.display_tips }}</view>
				<view class="discount-wrapper" >
					<view class="discount-item" v-if="!showDiscountMask && discount_type == 'coupon'">
						<view class="img-box"><image class="img" :src="requestDomain + 'static/images/pay_ico/discount1.png'" mode=""></image></view>
						<view class="desc">
							<view class="name"><lang keywords="优惠通道"></lang></view>
							<view class="txt"><lang keywords="此通道除了不可获取平台积分，其他优惠均可享受"></lang></view>
							<view class="change-btn" @click="clickShowMask">
								<lang keywords="修改通道"></lang>
								<text class="iconfont icon-jiantou"></text>
							</view>
						</view>
					</view>
					<view class="discount-item score" v-if="!showDiscountMask && discount_type == 'score'">
						<view class="img-box"><image class="img" :src="requestDomain + 'static/images/pay_ico/discount2.png'" mode=""></image></view>
						<view class="desc">
							<view class="name"><lang keywords="积分通道"></lang></view>
							<view class="txt"><lang keywords="此通道支付时只可获得平台积分，其他商家会员卡折扣、平台\商家优惠等优惠均不可享受"></lang></view>
							<view class="change-btn" @click="clickShowMask">
								<lang keywords="修改通道"></lang>
								<text class="iconfont icon-jiantou"></text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="pay-type" v-if="order_info.pay_config.is_recharge != 1 && order_info.only_pay != 1">
				<view class="line flex rel border-b" v-if="showCoupon && order_info.pay_config.card_discount != 0">
					<view class="left flex">
						<image class="icon" :src="requestDomain + 'static/images/pay_ico/member.png'"></image>
						<view class="desc">
							<view><lang keywords="会员卡折扣" /></view>
							<view class="gray"><lang keywords="运费不参与折扣" /></view>
						</view>
					</view>
					<view class="right flex">
						<view class="desc red">{{ order_info.pay_config.card_discount }}折</view>
					</view>
				</view>
				<view class="line flex rel border-b" v-if="showCoupon && order_info.pay_config.wx_cheap > 0">
					<view class="left flex">
						<image class="icon" :src="requestDomain + 'static/images/pay_ico/weixin-discount.png'"></image>
						<view class="desc">
							<view><lang keywords="微信优惠" /></view>
						</view>
					</view>
					<view class="right flex">
						<view class="desc red">-{{ currency + order_info.pay_config.wx_cheap }}</view>
					</view>
				</view>
				<view class="line flex rel border-b" v-if="showCoupon && order_info.order_info.pay_merchant_coupon !== false" @tap="changeMerchantCoupon">
					<view class="left flex">
						<image class="icon" :src="requestDomain + 'static/images/pay_ico/shop-coupon.png'"></image>
						<view class="desc">
							<view><lang keywords="商家优惠券" /></view>
							<view class="gray"><lang keywords="部分商品不可用商家优惠券" /></view>
						</view>
					</view>
					<view class="right flex">
						<view class="desc" v-if="order_info.mer_coupon.had_id == ''">
							<lang v-if="order_info.has_merchant_coupon == 1" keywords="不使用优惠券" />
							<lang v-else keywords="无可用优惠券" />
						</view>
						<view class="desc red" v-if="order_info.mer_coupon.had_id">
							<lang
								v-if="order_info.mer_coupon.order_money > 0"
								style="color:#FF1940"
								keywords="满X1减X2"
								:X1="order_info.mer_coupon.order_money"
								:X2="order_info.mer_coupon.discount"
							></lang>
							<lang v-else style="color:#FF1940" keywords="无门槛立减X1" :X1="order_info.mer_coupon.discount_value"></lang>
						</view>

						<text class="iconfont icon-jiantou"></text>
					</view>
				</view>
				<view class="line flex rel border-b" @tap="changeSystemCoupon" v-if="showCoupon && order_info.order_info.pay_system_coupon !== false">
					<view class="left flex">
						<image class="icon" :src="requestDomain + 'static/images/pay_ico/plat-coupon.png'"></image>
						<view class="desc">
							<view><lang keywords="平台优惠券"></lang></view>
						</view>
					</view>
					<view class="right flex">
						<view class="desc" v-if="order_info.system_coupon.had_id == ''">
							<lang v-if="order_info.has_system_coupon == 1" keywords="不使用优惠券"></lang>
							<lang v-else keywords="无可用优惠券" />
						</view>
						<view class="desc red" v-else>{{ order_info.system_coupon.coupon_des }}</view>
						<text class="iconfont icon-jiantou"></text>
					</view>
				</view>
				<view class="line flex rel border-b" v-if="order_info.pay_config.score_count != 0">
					<view class="left flex">
						<image class="icon" :src="requestDomain + 'static/images/pay_ico/score@2x.png'"></image>
						<view class="desc">
							<lang keywords="本单可使用"></lang>
							<text>{{ config.score_name }}</text>
							<text class="red">{{ order_info.pay_config.score_count }}</text>
							，
							<lang keywords="可抵扣金额"></lang>
							<view class="red block-in">{{ currency + order_info.pay_config.score_money }}</view>
						</view>
					</view>
					<switch color="#FF1940" :checked="use_score" @change="changeScore"></switch>
				</view>
				<view class="line flex rel border-b" v-if="order_info.pay_config.merchant_money != 0">
					<view class="left flex">
						<image class="icon" :src="requestDomain + 'static/images/pay_ico/merchant_balance@2x.png'"></image>
						<view class="desc">
							<lang keywords="商家会员卡余额"></lang>
							{{ currency + order_info.pay_config.merchant_money }}
						</view>
					</view>
					<switch color="#FF1940" :checked="use_merchant_money" @change="changeMm"></switch>
				</view>
				<view class="line flex rel border-b" v-if="order_info.pay_config.balance_money != 0">
					<view class="left flex">
						<image class="icon" :src="requestDomain + 'static/images/pay_ico/balance@2x.png'"></image>
						<view class="desc">
							<lang keywords="平台余额"></lang>
							{{ currency + order_info.pay_config.balance_money }}
						</view>
					</view>
					<switch color="#FF1940" :checked="use_balance_money" @change="changePm"></switch>
				</view>
			</view>

			<view class="pay-type" v-if="order_info.pay_config.online_pay != 0">
				<view class="title"><lang keywords="选择支付方式"></lang></view>
				<view class="line flex rel border-b" v-for="(item, index) in order_info.pay_method" :key="item.type" @tap="selectPayType(index)">
					<view class="left flex">
						<image class="icon" :src="item.pic"></image>
						<view class="desc">
							<view class="flex">
								{{ item.name }}
								<block v-if="item.service_charge > 0"><lang class="tip" keywords="X1%手续费" :X1="item.service_charge"></lang></block>
							</view>
							<view class="discount red" v-if="item.discount_tips != ''">
								<text class="iconfont icon-youhui1"></text>
								<text>{{ item.discount_tips }}</text>
							</view>
						</view>
					</view>
					<view class="right">
						<text class="iconfont icon-radio1" v-if="item.type != pay_type"></text>
						<text class="iconfont icon-radio2" v-else></text>
					</view>
				</view>
			</view>

			<view class="btn-box" @tap="payOrder">
				<button>
					<view v-if="order_info.pay_config.online_pay > 0">
						<lang keywords="去支付"></lang>
						{{currency + order_info.pay_config.online_pay}}
					</view>
					<view v-if="order_info.pay_config.online_pay == 0">
						<lang keywords="确认支付"></lang>
						<text v-if="order_info.pay_config.offline_pay">{{currency + order_info.pay_config.offline_pay}}</text>
					</view>
				</button>
			</view>

			<view class="discount-mask" v-if="showDiscountMask">
				<view class="discount-content">
					<view class="title">
						<lang keywords="选择优惠通道"></lang>
						<lang class="tip" keywords="（2选1且必选)"></lang>
					</view>
					<view class="discount-item" @click="selectDiscount('coupon')">
						<view class="img-box"><image class="img" :src="requestDomain + 'static/images/pay_ico/discount1.png'" mode=""></image></view>
						<view class="desc">
							<view class="name"><lang keywords="优惠通道"></lang></view>
							<view class="txt"><lang keywords="此通道除了不可获取平台积分，其他优惠均可享受"></lang></view>
						</view>
						<view :class="'select ' + (discount_type == 'coupon' ? 'active' : '')"></view>
					</view>
					<view class="discount-item score" @click="selectDiscount('score')">
						<view class="img-box"><image class="img" :src="requestDomain + 'static/images/pay_ico/discount2.png'" mode=""></image></view>
						<view class="desc">
							<view class="name"><lang keywords="积分通道"></lang></view>
							<view class="txt"><lang keywords="此通道支付时只可获得平台积分，其他商家会员卡折扣、平台\商家优惠等优惠均不可享受"></lang></view>
						</view>
						<view :class="'select ' + (discount_type == 'score' ? 'active' : '')"></view>
					</view>
				</view>
			</view>
		</view>

		<userinfo id="user" :options="user_options" @getUserscope="getUserInfo" @toLogin="getUserInfo"></userinfo>
	</view>
</template>

<script>
import common from '../../../utils/common.js';
var polyfill = require('../../../utils/base64.min.js');
var { atob, btoa } = polyfill;
var app = getApp();
var _this = '';
const clearStorage = () => {
	console.log('55555555555555清除购物车缓存');
	var store_id = _this.order_info.order_info.store_id;
	var store = wx.getStorageSync('store' + store_id);
	if (!store) {
		return
	}
	var pages = getCurrentPages();
	var prevPage = pages[pages.length - 3];
	wx.removeStorageSync('shop_cart_' + store_id);
	
	if (store && store.selectGoods && store.selectGoods.length > 0) {
		store.selectGoods = store.selectGoods.filter(item => item.selected === false);
	}
	if ((store.selectGoods && store.selectGoods.length == 0) || prevPage.route != 'pages/shop_new/cart/cart') {
		var ids = wx.getStorageSync('storeId_list');
		ids = ids.filter(item => item != store_id);
		wx.setStorageSync('storeId_list', ids);
		wx.removeStorageSync('store' + store_id);
	} else {
		var selectType = {};
		var goodsNumList = {};
		var totalNum = 0;
		var selectGoods = store.selectGoods;

		for (var i = 0; i < selectGoods.length; i++) {
			if (selectType[selectGoods[i].sort_id]) {
				selectType[selectGoods[i].sort_id] = selectType[selectGoods[i].sort_id] + selectGoods[i].selectNum;
			} else {
				selectType[selectGoods[i].sort_id] = selectGoods[i].selectNum;
			}

			goodsNumList[selectGoods[i].product_id] = selectGoods[i].selectNum;
			totalNum = totalNum + selectGoods[i].selectNum;
		}

		store.selectType = selectType;
		store.goodsNumList = goodsNumList;
		store.totalNum = totalNum;
		wx.setStorageSync('store' + store_id, store);
	}

	if (_this.cartId != '') {
		wx.removeStorageSync('togetherId_' + store_id);
		wx.removeStorageSync('together_cart_' + store_id);
		wx.removeStorageSync('pinId_' + store_id);
	}
};

export default {
	data() {
		return {
			page_from: '',
			order_id: 0,
			order_type: '',
			order_info: '',
			use_score: false,
			use_merchant_money: false,
			// 使用商家余额
			use_balance_money: false,
			// 使用平台余额
			use_sys_coupon: true,
			// 使用平台优惠券
			use_mer_coupon: true,
			// 使用商家优惠券
			system_coupon_id: 0,
			merchant_coupon_id: 0,
			config: {},
			click_confirm: false,
			wxRedirectUrl: '',
			pay_type: '', // 标记支付方式，不包括余额支付
			requestDomain: common.requestDomain,
			user_options: {},
			showCoupon: false, // 是否显示选择优惠券
			mobile_head_color: '',
			discount_type: '',
			showDiscountMask: false,
			currency: '¥',
			is_pay_for_others: 0 // 0非代付 1代付
		};
	},

	onShow: function() {
		// 页面显示
		var that = this;
		wx.getStorage({
			key: 'coupon_action',
			success: function(res) {
				var needCheck = false;
				var coupon_type = wx.getStorageSync('coupon_type');
				wx.removeStorage({
					key: 'coupon_action'
				});
				wx.removeStorage({
					key: 'coupon_type'
				});

				if (res.data == 'not') {
					needCheck = true;
					if (coupon_type == 'system') {
						_this.use_sys_coupon = false;
					} else {
						_this.use_mer_coupon = false;
					}
				} else if (res.data == 'use') {
					needCheck = true;
					if (coupon_type == 'system') {
						_this.use_sys_coupon = true;
						_this.system_coupon_id = wx.getStorageSync('coupon_id');
					} else {
						_this.use_mer_coupon = true;
						_this.merchant_coupon_id = wx.getStorageSync('coupon_id');
					}

					wx.removeStorage({
						key: 'coupon_id'
					});
				}

				if (needCheck) {
					console.log('paycheck1111111111');
					that.paycheck();
				}
			}
		});

		// #ifdef MP-WEIXIN
		if (that.pageTime == true && that.pay_type != 'weixin') {
			// 不是第一次进入页面且支付方式选的不是微信支付
			that.paycheckState = 'back';
			console.log('paycheck22222222222');
			that.paycheck();
		}
		// #endif

		// #ifdef MP-ALIPAY
		if (that.pageTime == true && that.pay_type != 'alipay') {
			// 不是第一次进入页面且支付方式选的不是支付宝支付
			that.paycheckState = 'back';
			console.log('paycheck3333333333');
			that.paycheck();
		}
		// #endif

		// #ifdef H5
		if ((that.pay_type == 'alipay' && common.$checkPlat.checkAlipay()) || (that.pay_type == 'weixin' && common.$checkPlat.checkWeixin())) {
			// 支付宝浏览器中选择支付宝支付
		} else if (that.pageTime == true) {
			// 不是第一次进入页面且支付方式选的不是微信支付
			that.paycheckState = 'back';
			console.log('paycheck4444444444');
			that.paycheck();
		}
		// #endif

		if (that.weixinPayOk == true || that.aliPayOk == true) {
			// 微信原生支付成功  或者  支付宝原生支付成功
			this.paySuccessBack();
			console.log('原生弹窗支付成功返回');
		} else {
			_this.click_confirm = false;
		}
		that.pageTime = true;

		// #ifdef H5
		common.hideWxShare();
		// #endif
	},
	onLoad: function(options) {
		console.log('支付页初始化', options);
		_this = this;
		if (!options.is_pay_for_others) {
			if (typeof options.merchant_coupon_id == 'undefined') {
				this.showCoupon = true;
			} else {
				_this.use_sys_coupon = options.use_sys_coupon == 'true' ? true : false;
				_this.use_mer_coupon = options.use_mer_coupon == 'true' ? true : false;
				_this.merchant_coupon_id = options.merchant_coupon_id;
				_this.system_coupon_id = options.system_coupon_id;
			}
		} else {
			_this.is_pay_for_others = options.is_pay_for_others;
		}

		_this.order_id = options.order_id;
		_this.order_type = options.type;
		_this.page_from = options.from ? options.from : '';
		_this.pay_type = options.pay_type ? options.pay_type : '';

		app.globalData.isPay = true;

		// #ifdef H5
		// if (!options.isHavePlatNativePay) {
		// 	common.webToMiniapp('/pages/shop_new/confirmOrder/pay', options)
		// }
		if (common.$checkPlat.checkApp()) {
			let param = { name: 'payCheckNew', orderID: options.order_id, type: options.type };
			if (typeof options.merchant_coupon_id == 'undefined') {
				param.showCoupon = true;
			} else {
				param.showCoupon = false;
				param.use_sys_coupon = options.use_sys_coupon;
				param.sys_id = options.system_coupon_id;
				param.use_mer_coupon = options.use_mer_coupon;
				param.mer_id = options.merchant_coupon_id;
			}

			if (common.$checkPlat.checkAndroid()) {
				if (common.$checkPlat.getAppVersion() < 1600) {
					window.lifepasslogin.payCheck(options.type, options.order_id);
				} else {
					window.lifepasslogin.payCheckNew(JSON.stringify(param));
				}
			} else {
				window.webkit.messageHandlers.appJSBridgeMethod.postMessage(param);
			}
			return;
		}
		// #endif

		// #ifdef MP-WEIXIN || MP-ALIPAY
		if (app.globalData.is_login || options.type == 'store' || (options.type == 'plat' && options['order_from'] == 1)) {
			console.log('paycheck 888');
			_this.paycheck();
		} else {
			_this.user_options = {
				toLogin: true,
				refuseIsShow: true,
				showCancel: false
			};
		}
		// #endif

		// #ifdef H5
		console.log('2222options=', options, app.globalData.is_login, app.globalData.userInfo);
		let ticket = '';
		// type=store 或者type=plat&&order_from=1 不用登录
		if (!app.globalData.is_login && options.ticket) {
			ticket = options.ticket;
			app.globalData.is_login = true;
			uni.setStorageSync('ticket', ticket);
			common.$dataStorage.cookie.set('login_status', 'login');
			common.$dataStorage.cookie.set('user_ticket', ticket);
			common.$dataStorage.cookie.set('user_device_id', 'packapp');
		}
		if (app.globalData.is_login || options.type == 'store' || (options.type == 'plat' && options['order_from'] == 1)) {
			_this.paycheck();
		} else {
			uni.showModal({
				title: common.changeTxt('提示'),
				content: common.changeTxt('支付前请先登录'),
				showCancel: false,
				confirmText: common.changeTxt('去登录'),
				success: function(res) {
					_this.user_options = {
						toLogin: true,
						refuseIsShow: true,
						showCancel: false
					};
				}
			});
		}
		// #endif
		common.changeCurrency(this);
	},
	mounted() {
		common.setMainColor(_this, function() {
			common.getTxtKey('支付订单').then(function(data) {
				uni.setNavigationBarTitle({
					title: data
				});
			});
		});
		// #ifdef H5
		window.onload = function() {
			window.ReturnLastPay = function() {
				history.back();
			};
		};
		// #endif
	},
	methods: {
		clickShowMask() {
			_this.showDiscountMask = true;
		},
		selectDiscount(type) {
			_this.discount_type = type;
			_this.showDiscountMask = false;
			this.paycheck();
		},
		selectPayType(index) {
			_this.payMethod = _this.order_info.pay_method[index];
			var pay_type = _this.payMethod.type;

			if (pay_type != _this.pay_type) {
				_this.pay_type = pay_type;
				this.paycheck();
			}
		},

		changeScore: function(e) {
			console.log(e);
			this.use_score = !this.use_score;
			console.log('paycheck 666');
			this.paycheck();
		},
		changeMm: function(e) {
			console.log(e);

			if (this.use_balance_money && !this.use_merchant_money && this.order_info.pay_config.online_pay == 0) {
				this.use_balance_money = false;
			}

			this.use_merchant_money = !this.use_merchant_money;
			console.log('paycheck 555');
			this.paycheck();
		},
		changePm: function(e) {
			console.log(e);

			if (this.use_merchant_money && !this.use_balance_money && this.order_info.pay_config.online_pay == 0) {
				this.use_merchant_money = false;
			}

			this.use_balance_money = !this.use_balance_money;
			console.log('paycheck 444');
			this.paycheck();
		},
		changeMerchantCoupon: function(e) {
			console.log(e);

			if (e.type == 'submit') {
				common.upFormid(e);
			}

			wx.navigateTo({
				url: '/pages/pay/coupon?order_id=' + this.order_id + '&type=' + this.order_type + '&coupon_type=mer&coupon_id=' + this.merchant_coupon_id
			});
		},
		changeSystemCoupon: function(e) {
			console.log(e);

			if (e.type == 'submit') {
				common.upFormid(e);
			}

			wx.navigateTo({
				url: '/pages/pay/coupon?order_id=' + this.order_id + '&type=' + this.order_type + '&coupon_type=system&coupon_id=' + this.system_coupon_id
			});
		},
		paycheck: function() {
			wx.showToast({
				title: common.changeTxt('请求中'),
				icon: 'loading',
				duration: 10000,
				mask: true
			});
			var postData = {};
			postData.type = this.order_type;
			postData.order_id = this.order_id;
			postData.use_score = this.use_score;
			postData.use_merchant_money = this.use_merchant_money;
			postData.use_balance_money = this.use_balance_money;
			postData.use_mer_coupon = this.use_mer_coupon;
			postData.use_sys_coupon = this.use_sys_coupon;
			postData.system_coupon_id = this.system_coupon_id;
			postData.merchant_coupon_id = this.merchant_coupon_id;
			postData.pay_type = this.pay_type;
			postData.page_from = 'pay';
			postData.discount_type = _this.discount_type;
			postData.is_pay_for_others = _this.is_pay_for_others;

			common.post('Pay&a=check', postData, 'setPageContent', this, 'getOrderErr');
		},
		setPageContent: function(result) {
			console.log('paycheck 请求结果', result);
			if (result.auth_url) {
				location.replace(result.auth_url);
				return;
			}

			var system_coupon_id = result.system_coupon.had_id != '' ? result.system_coupon.had_id : 0;
			var merchant_coupon_id = result.mer_coupon.had_id != '' ? result.mer_coupon.had_id : 0;

			if (result.system_coupon.had_id != '') {
				result.system_coupon.order_money = parseFloat(result.system_coupon.order_money);
			}

			if (result.mer_coupon.had_id != '') {
				result.mer_coupon.order_money = parseFloat(result.mer_coupon.order_money);
			}

			if (result.pay_method && result.pay_method.length > 0 && !this.pay_type) {
				this.pay_type = result.pay_method[0].type;
				this.payMethod = result.pay_method[0];
			} else if (result.pay_method && result.pay_method.length > 0 && this.pay_type) {
				for (let i = 0; i < result.pay_method.length; i++) {
					if (result.pay_method[i].type == this.pay_type) {
						this.payMethod = result.pay_method[i];
						break;
					}
				}
			}

			this.order_info = result;
			this.system_coupon_id = system_coupon_id;
			this.merchant_coupon_id = merchant_coupon_id;
			this.click_confirm = false;
			if (!this.discount_type && result.user_discount_type > 0) {
				this.discount_type = 'coupon';
				this.showDiscountMask = result.user_discount_type == 3;
			}
			wx.hideToast();
		},
		getOrderErr: function(res) {
			// #ifdef H5
			console.log('paycheck 错误');
			if (res.errorCode == 20049999 || res.errorCode == 20049998) {
				console.log('paycheck 错误222');
				uni.setStorageSync('shopRefresh', 'true');
				common.navigateBack();
			} else {
				uni.showModal({
					title: common.changeTxt('提示'),
					content: res.errorMsg,
					showCancel: false,
					success: () => {
						common.navigateBack();
					}
				});
			}
			// #endif

			// #ifdef MP-WEIXIN || MP-ALIPAY
			if (res.errorCode == 1) {
				this.payOkRedirect();
			} else if ((res.errorCode == 20049999 || res.errorCode == 20049998) && _this.paycheckState === 'back') {
				this.paySuccessBack();
			} else {
				wx.hideToast();
				wx.showModal({
					title: common.changeTxt('提示'),
					content: res.result && res.result.msg ? res.result.msg : res.errorMsg,
					showCancel: false,
					success: function() {
						if (_this.paycheckState !== 'back') {
							wx.navigateBack();
							console.log('首次打开页面且订单页面报错');
						} else {
							_this.click_confirm = false;

							_this.paycheckState == '';
						}
					}
				});
			}
			// #endif
		},

		paySuccessBack() {
			if (this.order_type == 'shop') {
				uni.setStorageSync('shopRefresh', true);
				// 清除缓存
				clearStorage();
				var pages = getCurrentPages();
				var prevPage = pages[pages.length - 3];
				prevPage.data.refresh = true;
				var num = 1;

				for (var i = 0; i < pages.length; i++) {
					if (pages[i].route.indexOf('newCart') != -1) {
						console.log('222222222222222211113333', num, pages, i);
						num = pages.length - i;
						break;
					}
				}

				wx.navigateBack({
					delta: num
				});
				console.log('从上一页面回退回来，且是余额支付');
			} else if (this.order_type == 'plat' && this.order_info.order_info.business_type == 'village_group') {
				if (app.globalData.tabBar.list.length == 1) {
					app.globalData.tabWeb = {
						url: 'https://hf.pigcms.com/wap.php?g=Wap&c=Village_group&a=my&leader_id=' + _this.order_info.order_info.order_info.start_uid,
						title: common.changeTxt('社区团购')
					};
					wx.reLaunch({
						url: '/pages/webview/tab_webview'
					});
				} else {
					wx.reLaunch({
						url:
							'../index/index?redirect=webview&webview_url=' +
							encodeURIComponent('https://hf.pigcms.com/wap.php?g=Wap&c=Village_group&a=my&leader_id=' + _this.order_info.order_info.order_info.start_uid) +
							'&webview_title=' +
							encodeURIComponent('社区团购')
					});
				}
			} else if (this.order_type == 'plat' && this.order_info.order_info.business_type == 'house_village_pay') {
				wx.reLaunch({
					url:
						'../index/index?redirect=webview&webview_url=' +
						encodeURIComponent('/wap.php?c=House&a=village_my&village_id=' + this.order_info.order_info.order_info.village_id)
				});
			} else {
				if (common.checkIsFooterPage('/pages/plat_menu/my')) {
					wx.switchTab({
						url: '/pages/plat_menu/my'
					});
				} else if (common.checkIsFooterPage('/pages/village/my/myindex')) {
					wx.switchTab({
						url: '/pages/village/my/myindex'
					});
				} else {
					wx.reLaunch({
						url: app.globalData.tabBar.list[0].pagePath
					});
				}
			}
		},

		payOrder: function(e) {
			console.log(e); 
			if (e.type == 'submit') {
				common.upFormid(e);
			}

			if (_this.click_confirm == true) {
				return;
			}

			_this.click_confirm = true;

			wx.showToast({
				title: common.changeTxt('请求中'),
				icon: 'loading',
				duration: 10000,
				mask: true
			});
			var postData = {};
			postData.order_type = this.order_type;
			postData.order_id = this.order_id;
			postData.pay_type = this.order_info.pay_config.online_pay != 0 ? this.pay_type : '';
			postData.use_sys_coupon = this.use_sys_coupon;
			postData.use_mer_coupon = this.use_mer_coupon;
			postData.coupon_id = this.system_coupon_id;
			postData.card_id = this.merchant_coupon_id;
			postData.use_score = this.use_score;
			postData.use_merchant_money = this.use_merchant_money;
			postData.use_balance_money = this.use_balance_money;
			postData.score_used_count = this.order_info.pay_config.score_count;
			postData.score_deducte = this.order_info.pay_config.score_money;
			if (app.merchantOwn && app.merchantOwn.mer_id) {
				postData.own_pay_mer_id = app.merchantOwn.mer_id;
			}
			postData.ticket = uni.getStorageSync('ticket');
			postData.is_pay_for_others = _this.is_pay_for_others;

			console.log('去支付11111111111',postData.pay_type,_this.payMethod.submit_to);
			// #ifdef MP-WEIXIN
			if (postData.pay_type == 'weixin' && _this.payMethod.submit_to != 'wap') {
				// 微信支付
				common.post('Pay&a=go_pay', postData, 'getOrderId', this, 'getOrderIdErr');
				return;
			}
			// #endif

			// #ifdef MP-ALIPAY
			if (postData.pay_type == 'alipay' && _this.payMethod.submit_to != 'wap') {
				// 微信支付
				common.post('Pay&a=go_pay', postData, 'getOrderId', this, 'getOrderIdErr');
				return;
			}
			// #endif

			// #ifdef H5
			// 清除缓存
			clearStorage();
			if (postData.pay_type == 'weixin' && common.$checkPlat.checkWeixin() && _this.payMethod.submit_to != 'wap') {
				// 微信支付
				common.post('Pay&a=go_pay', postData, 'getOrderId', this, 'getOrderIdErr');
				return;
			} else if (postData.pay_type == 'alipay' && common.$checkPlat.checkAlipay() && _this.payMethod.submit_to != 'wap') {
				// 支付宝支付
				common.post('Pay&a=go_pay', postData, 'getOrderId', this, 'getOrderIdErr');
				return;
			}
			// #endif

			console.log('去支付3333333');
			wx.setStorageSync('order_from', 'pay');

			var pay_param = encodeURIComponent(btoa(JSON.stringify(postData)));
			var requestDomain = common.requestDomain;
			var url = `${requestDomain}wap.php?c=Pay&a=go_pay&wxapp_error_handle=close_window&device_id=packapp&ticket=${postData.ticket}&pay_param=${pay_param}`;
			console.log('去支付', url);
			common.parseUrl(url);
		},
		onBridgeReady(res) {
			WeixinJSBridge.invoke('getBrandWCPayRequest', res.weixin_param, function(res) {
				console.log('h5调用微信支付', res);
				if (res.err_msg == 'get_brand_wcpay_request:ok') {
					// 使用以上方式判断前端返回,微信团队郑重提示：
					//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
					var postData = {
						order_id: _this.order_id,
						order_type: _this.order_type
					};
					common.post('Pay&a=app_weixin_back', postData, 'payOk', _this, 'payOkErr');
				} else {
					_this.click_confirm = false;
				}
			});
		},
		getOrderId: function(res) {
			console.log('点击确认支付 获取支付ID', res);

			var postData = {
				order_id: _this.order_id,
				order_type: _this.order_type
			};
			_this.wxRedirectUrl = '';
			if (res.redirctUrl) {
				_this.wxRedirectUrl = res.redirctUrl;
				console.log('_this.wxRedirectUrl', _this.wxRedirectUrl);
			}

			// #ifdef H5
			if (_this.pay_type == 'weixin') {
				if (typeof WeixinJSBridge == 'undefined') {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', _this.onBridgeReady(res), false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', _this.onBridgeReady(res));
						document.attachEvent('onWeixinJSBridgeReady', _this.onBridgeReady(res));
					}
				} else {
					_this.onBridgeReady(res);
				}
			} else if (_this.pay_type == 'alipay') {
				let obj = {};
				if (res.orderStr) {
					obj = { orderStr: res.orderStr };
				} else {
					obj = { tradeNO: res.tradeNO };
				}
				ap.tradePay(obj, function(res) {
					if (res.resultCode == 9000) {
						if (_this.wxRedirectUrl) {
							_this.click_confirm = false;
							common.parseUrl(_this.wxRedirectUrl);
						} else {
							postData.trade_no = res.orderStr;
							common.post('Pay&a=app_alipay_back', postData, 'payOk', _this, 'payOkErr');
						}
					} else {
						_this.click_confirm = false;
					}
				});
			}
			// #endif

			// #ifdef MP-ALIPAY
			my.tradePay({
				// 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
				tradeNO: res.orderStr,
				success: results => {
					console.log('支付success', results);
					if (results.resultCode == 9000) {
						postData.trade_no = res.orderStr;
						common.post('Pay&a=app_alipay_back', postData, 'payOk', _this, 'payOkErr');
					}
				},
				fail: res => {
					console.log('支付fail', res);
					_this.click_confirm = false;
				}
			});
			return;
			// #endif

			// #ifdef MP-WEIXIN
			wx.requestPayment({
				timeStamp: res.weixin_param.timeStamp,
				nonceStr: res.weixin_param.nonceStr,
				package: res.weixin_param.package,
				signType: res.weixin_param.signType,
				paySign: res.weixin_param.paySign,
				success: function(ress) {
					console.log(ress);

					if (app.merchantOwn && app.merchantOwn.mer_id) {
						postData.own_pay_mer_id = app.merchantOwn.mer_id;
					}

					common.post('Pay&a=app_weixin_back', postData, 'payOk', _this, 'payOkErr');
				},
				fail: function(ress) {
					console.log(ress);
					_this.click_confirm = false;
				}
			});
			// #endif
			wx.hideToast();
		},
		payOk: function(res) {
			wx.showModal({
				title: common.changeTxt('提示'),
				content: common.changeTxt('支付成功'),
				showCancel: false,
				success: function() {
					if (_this.is_pay_for_others == 1) {
						common.navigateBack();
						return;
					}

					// #ifdef MP-WEIXIN
					_this.weixinPayOk = true;
					_this.payOkRedirect(res);
					// #endif

					// #ifdef MP-ALIPAY
					_this.aliPayOk = true;
					_this.payOkRedirect(res.url);
					// #endif

					// #ifdef H5
					console.log('h5微信支付成功', res);
					if (_this.pay_type == 'weixin') {
						_this.weixinPayOk = true;
						_this.payOkRedirect(res);
					} else if (_this.pay_type == 'alipay') {
						_this.aliPayOk = true;
						_this.payOkRedirect(res.url);
					}
					// #endif
				}
			});
		},
		payOkRedirect: function(url) {
			if (this.page_from == 'otherWxapp') {
				if (this.order_type == 'plat') {
					if (this.order_info.order_info.business_type == 'service') {
						wx.showModal({
							title: common.changeTxt('提示'),
							content: common.changeTxt('支付成功'),
							showCancel: false,
							success: function() {
								wx.reLaunch({
									url:
										'/pages/index/location?redirect=webview&webview_url=' +
										encodeURIComponent('https://hf.pigcms.com/wap.php?c=Service&a=price_list&publish_id=' + that.order_info.order_info.order_info.publish_id) +
										'&webview_title=' +
										encodeURIComponent('需求详情')
								});
							}
						});
					}
				}

				return false;
			}

			if (this.order_type == 'shop') {
				// 清除缓存
				clearStorage();
			}

			if (url && this.order_type == 'shop') {
				common.parseUrl(url);
			} else if (this.order_type == 'plat' && this.order_info.order_info.business_type == 'village_group') {
				common.parseUrl(url);
			} else if (this.order_type == 'plat' && this.order_info.order_info.business_type == 'house_village_pay') {
				wx.reLaunch({
					url:
						'../index/index?redirect=webview&webview_url=' +
						encodeURIComponent('/wap.php?c=House&a=village_my&village_id=' + this.order_info.order_info.order_info.village_id + '&go_action=village_my_paylists')
				});
			} else {
				wx.setStorageSync('my_redirect_type', this.order_type);
				console.log('支付成功跳转', url);
				common.parseUrl(url);
			}
		},
		payOkErr: function(res) {
			console.log(res);
			if (_this.wxRedirectUrl) {
				common.parseUrl(_this.wxRedirectUrl);
			}
			_this.click_confirm = false;
		},
		getOrderIdErr: function(res) {
			console.log('weixin pay error', res);
			wx.hideToast();

			if (res.errorCode == 1) {
				var that = this;
				wx.showModal({
					title: common.changeTxt('提示'),
					content: common.changeTxt('支付成功'),
					showCancel: false,
					success: function() {
						that.payOkRedirect();
					}
				});
			} else {
				_this.click_confirm = false;

				wx.showModal({
					title: common.changeTxt('提示'),
					content: res.errorMsg,
					showCancel: false
				});
			}
		},

		getUserInfo(e) {
			if (e.userInfo && e.userInfo.wxapp_openid != '') {
				console.log('paycheck 333');
				_this.paycheck();
			} else {
				common.log_report('pages/shop_new/confirmOrder/pay.js 用户信息中没有wxapp_openid');
			}
		}
	}
};
</script>
<style>
page {
	background: #f7f7f7;
}
.page-wrapper {
	padding-bottom: 130px;
}
.wx-switch-input {
	width: 40px !important;
	height: 24px !important;
	border: 1px solid #aaa;
}

.wx-switch-input::before {
	width: 38px !important;
	height: 22px !important;
}

.wx-switch-input::after {
	width: 22px !important;
	height: 22px !important;
}

.border-b::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	height: 1rpx;
	background: #ccc;
	transform: scaleY(0.5);
}

.rel {
	position: relative;
}

.flex {
	display: flex;
	align-items: center;
}

.order-num {
	background: rgba(255, 153, 0, 0.1);
	color: #535353;
	font-size: 12px;
	text-align: center;
	padding: 3px 0;
}

.pay-num {
	background: #fff;
	text-align: center;
	padding: 15px 0;
}

.pay-num .num-box {
	font-size: 14px;
}

.pay-num .num-box .num {
	color: #ff1940;
}

.pay-num .desc-box {
	font-size: 11px;
	color: #7d7d7d;
	line-height: 2;
}

.line {
	padding: 15px 15px 15px 20px;
	background: #fff;
}

.line .left {
	font-size: 15px;
	flex-grow: 1;
	padding-right: 15px;
}

.line .left .icon {
	width: 40px;
	height: 40px;
	flex-shrink: 0;
	margin-right: 10px;
}

.line .left .desc .red {
	color: #ff1940;
}

.line .left .desc .discount {
	font-size: 12px;
	margin-top: 2px;
}

.line .left .desc .discount .iconfont {
	margin-right: 2px;
	position: relative;
	top: 1px;
}

.line .left .desc .tip {
	border: 1px solid #aaa;
	color: #aaa;
	font-size: 10px;
	padding: 0 5px;
	border-radius: 2px;
	margin-left: 5px;
}

.line .left .desc .gray {
	font-size: 12px;
	color: #999;
}

.line .right {
	margin-right: 3px;
}

.line .right .icon-jiantou {
	color: #bbbbbb;
	font-size: 26px;
	margin-right: -8px;
}

.line .right .desc {
	font-size: 15px;
	color: #999;
}

.line .right .desc.red {
	color: #ff1940;
}

.line .right .icon-radio1 {
	color: #bbbbbb;
	font-size: 26px;
}

.line .right .icon-radio2 {
	color: #ff1940;
	font-size: 26px;
}

.title {
	font-size: 16px;
	padding: 10px 20px;
}

.pay-type .line:last-child::after {
	height: 0;
}

.btn-box {
	position: fixed;
	bottom: 30px;
	left: 50%;
	transform: translateX(-50%);
}

.btn-box button {
	background: #ff1940;
	color: #fff;
	width: auto;
	display: inline-block;
	border-radius: 30px;
	box-shadow: 0 0 10px 2px rgb(243, 180, 191);
	padding: 0 30rpx;
}
.discount-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.7);
	display: flex;
	justify-content: center;
	align-items: center;
}

.discount-mask .discount-content {
	background: #fff;
	width: 80%;
	border-radius: 10rpx;
}
.discount-mask .discount-content .title {
	text-align: center;
	padding: 20rpx 0;
}
.discount-mask .discount-content .title .tip {
	font-size: 12px;
	color: #999;
}
.discount-item {
	position: relative;
	margin: 0 20rpx 20rpx;
	padding: 40rpx 20rpx;
	border-radius: 10rpx;
	color: #fff;
	font-size: 13px;
	display: flex;
	align-items: center;
	background: -webkit-linear-gradient(to top right, rgba(255, 100, 151, 0.8), rgba(255, 153, 117, 0.8));
	background: -o-linear-gradient(to top right, rgba(255, 100, 151, 0.8), rgba(255, 153, 117, 0.8));
	background: -moz-linear-gradient(to top right, rgba(255, 100, 151, 0.8), rgba(255, 153, 117, 0.8));
	background: linear-gradient(to top right, rgba(255, 100, 151, 0.8), rgba(255, 153, 117, 0.8));
}

.discount-item.score {
	background: -webkit-linear-gradient(to top right, rgba(63, 189, 255, 0.8), rgba(47, 206, 255, 0.8));
	background: -o-linear-gradient(to top right, rgba(63, 189, 255, 0.8), rgba(47, 206, 255, 0.8));
	background: -moz-linear-gradient(to top right, rgba(63, 189, 255, 0.8), rgba(47, 206, 255, 0.8));
	background: linear-gradient(to top right, rgba(63, 189, 255, 0.8), rgba(47, 206, 255, 0.8));
}

.discount-item .img-box {
	width: 80rpx;
	height: 80rpx;
	flex-shrink: 0;
	margin-right: 20rpx;
}
.discount-item .img-box .img {
	width: 100%;
	height: 100%;
}

.discount-item .name {
	font-size: 16px;
}

.discount-item .select {
	position: absolute;
	right: 20rpx;
	top: 20rpx;
	border: 1px solid #fff;
	width: 40rpx;
	height: 40rpx;
	border-radius: 50%;
}
.discount-item .select.active {
	background: rgba(255, 255, 255, 0.9);
	box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.discount-item .change-btn {
	position: absolute;
	right: 0;
	bottom: 0;
	padding: 20rpx;
}
.discount-item .change-btn .iconfont {
	vertical-align: middle;
}
.discount-wrapper .discount-item {
	margin: 20rpx 20rpx 0;
	text-align: left;
}
.discount-wrapper .discount-item.score .desc {
	margin-bottom: 20rpx;
}
</style>
